<template>
  <MyModal ref="myModal" title="新增初语账户" :top="35">
    <template #content>
      <div style="display: grid; place-items: center">
        <a-form ref="formRef" :rules="rules" :model="formState" :label-col="labelCol" style="width: 360px">
          <a-form-item has-feedback name="IMid" label="客服ID">
            <a-input v-model:value.trim="formState.IMid" placeholder="客服ID"></a-input>
          </a-form-item>

          <a-form-item has-feedback name="remark" label="备注">
            <a-textarea v-model:value.trim="formState.remark" style="max-height: 260px" :maxlength="300"
              placeholder="备注"></a-textarea>
          </a-form-item>

          <a-form-item style="text-align: right">
            <a-button @click="myModal.cancelModal()" style="border-radius: 6px">取消</a-button>
            <a-button style="margin-left: 10px; border-radius: 6px" type="primary" @click="handleSubmit">
              确定
            </a-button>
          </a-form-item>
        </a-form>
      </div>
    </template>
  </MyModal>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import * as imApi from '@/api/im'
import { message } from 'ant-design-vue'

const myModal = ref()

let onlyType = ref<string>('wx')
const showModal = (type = 'wx') => {
  myModal.value?.showModal()
  onlyType.value = type
}

const emit = defineEmits<{
  refresh: []
}>()

defineExpose({
  showModal,
})

let labelCol = { span: 5 }
const formRef = ref()
interface formState {
  remark: string
  IMid: string
}
const formState = ref<formState>({
  remark: '',
  IMid: '',
})

import type { Rule } from 'ant-design-vue/es/form'
const rules: Record<string, Rule[]> = {
  IMid: [{ required: true, message: '请输入客服ID', trigger: 'blur' }],
}

const handleSubmit = async () => {
  formRef.value.validate().then(async () => {
    // console.log('formState=', formState.value)

    const params = {
      channel: onlyType.value == 'wx' ? 1 : 3, // 1:微信，3：闲鱼
      customerId: formState.value.IMid,
      remark: formState.value.remark,
    }

    try {
      let { state, message: msg } = await imApi.addCustomer(params)
      if (state === 200) {
        message.success('添加成功')
        myModal.value.cancelModal()
        emit('refresh')
      } else {
        message.error(msg)
      }
    } catch (error) {
      message.error('网络请求连接失败~')
    }
  })
}
</script>
